/*
 * @Author: duanguang
 * @Date: 2020-06-04 15:37:47
 * @LastEditTime: 2022-04-27 19:12:29
 * @LastEditors: duanguang
 * @Description: 
 * @FilePath: /legions-server/app/controller/branch.ts
 * 「扫去窗上的尘埃，才可以看到窗外的美景。」
 */
import ResponseModel,{ PageResponseModel } from '@/model/responseModel';
import { UserRoleEnum,auditStatusEnum } from '@/constants/enum.types';
import { roleAuthority } from '@/abstract/controller/decorators';
import CommonController from '@/abstract/controller/common';
import { HttpClientResponse } from 'urllib';
interface InterfaceQuery<T> {
  gitlab_project_id?: T;
  source_git_url?: T;
  id?: string
}
export default class BranchController extends CommonController {
  /**
   * 分支申请通过
   */
  public async checkout() {
    const query: Partial<InterfaceQuery<string>> = this.ctx.query;
    const result = await this.ctx.model.BranchApply.findById(query.id)
    if (result && result.assign_members_id === this.userInfo?.id) {
      const project_result = await this.ctx.curl<HttpClientResponse<string>>(`https://gitlab.hoolinks.com/api/v4/projects/${result.gitlab_project_id}/repository/branches`,{
        dataType: 'json',
        contentType: 'application/json',
        method: 'POST',
        headers: {
          Authorization: this.ctx.request.get('gitlab_authorization')
        },
        data: {
          ref: result.source_branch,
          branch: result.branch_name,
        },
      });
      if (project_result.data && project_result.data['name']) {
        await this.ctx.service.branch.branchApplyPass({
          id: query.id || '',
          userId: this.userInfo?.id || '',
          userRule: this.userInfo?.roleNo || -1,
          audit_status: auditStatusEnum.pass
        });
        this.ctx.body = new ResponseModel({
          success: true,
          data: project_result.data,
          message: '分支申请通过',
        });
        return
      }
      this.ctx.body = new ResponseModel({
        success: false,
        data: project_result.data,
        message: '分支申请失败',
      });
    }
  }
  /**
   * 获取指定仓库远程分支数据
   */
  public async index() {
    const query: Partial<InterfaceQuery<string>> = this.ctx.query;
    if (!query.gitlab_project_id) {
      this.ctx.body = new ResponseModel({
        success: false,
        data: [],
        message: 'gitlab_project_id 不能为空',
      });
    }
    const project_result = await this.ctx.curl<HttpClientResponse<string>>(`https://gitlab.hoolinks.com/api/v4/projects/${query.gitlab_project_id}/repository/branches`,{
      dataType: 'json',
      method: 'GET',
      headers: {
        Authorization: this.ctx.request.get('Authorization')
      }
    });
    this.ctx.body = new ResponseModel({
      data: project_result.data,
      message: '调用成功',
      success: true,
    });
  }
  /**
 * 分支申请
 *
 * @memberof RepositoryProjectController
 */
  @roleAuthority(UserRoleEnum.developer)
  public async apply() {
    const { ctx } = this;
    const { body } = ctx.request;
    const errors = this.app.validator.validate(
      {
        repository_name: { type: 'string',required: true },
        project_id: { type: 'string',required: true },
        source_branch: { type: 'string',required: true },
        branch_type: { type: 'string',required: true },
        branch_name: { type: 'string',required: true },
        gitlab_project_group: { type: 'string',required: true },
        gitlab_project_id: { type: 'string',required: true },
        repository_https: { type: 'string',required: true },
        branch_usage: { type: 'string',required: false },
        assign_members: { type: 'string',required: true },
        assign_members_id: { type: 'string',required: true },
      },
      body,
    )
    if (errors) {
      this.ctx.body = new ResponseModel({
        success: false,
        data: errors,
        message: '参数错误',
      });
      return;
    }
    try {

      const res = await this.ctx.service.branch.createBranchApply({
        ...body,
        creator_id: this.userInfo?.id,
        creator: this.userInfo?.name,
        audit_status: auditStatusEnum.waiting
      });
      this.ctx.body = new ResponseModel({
        success: true,
        data: res,
        message: '分支申请发起成功',
      });
    } catch (error) {
      this.ctx.body = new ResponseModel({
        success: false,
        // @ts-ignore
        message: error && error.toString(),
      });
    }
  }

  /**
   * 分支申请数据删除
   * @returns
   */
  @roleAuthority(UserRoleEnum.developer)
  public async delete() {
    const { ctx } = this;
    const { body } = ctx.request;
    const errors = this.app.validator.validate({
      id: { type: 'string' },
    },body);
    if (errors) {
      this.ctx.body = new ResponseModel({
        success: false,
        data: errors,
        message: '参数错误',
      });
      return;
    }
    try {
      const res = await this.ctx.service.branch.delete(body.id,this.userInfo?.roleNo || -1,this.userInfo?.id || '');
      this.ctx.body = new ResponseModel({
        success: true,
        data: res,
        message: '删除成功',
      });
    } catch (error) {
      this.ctx.body = new ResponseModel({
        success: false,
        // @ts-ignore
        message: error,
      });
    }
  }
  /**
   * 驳回分支申请
   * @returns 
   */
  @roleAuthority(UserRoleEnum.developer)
  public async reject() {
    const { ctx } = this;
    const { body } = ctx.request;
    const errors = this.app.validator.validate({
      id: { type: 'string' },
    },body);
    if (errors) {
      this.ctx.body = new ResponseModel({
        success: false,
        data: errors,
        message: '参数错误',
      });
      return;
    }
    try {
      const res = await this.ctx.service.branch.reject(body.id,this.userInfo?.roleNo || -1,this.userInfo?.id || '');
      this.ctx.body = new ResponseModel({
        success: true,
        data: res,
        message: '驳回成功',
      });
    } catch (error) {
      this.ctx.body = new ResponseModel({
        success: false,
        // @ts-ignore
        message: error,
      });
    }
  }
  /**
   * 分支申请数据列表
   */
  @roleAuthority(UserRoleEnum.developer)
  public async list() {
    const query = this.ctx.query as any;
    try {
      const res = await this.ctx.service.branch.getList({
        ...query,
        userRule: this.userInfo?.roleNo,
        userId: this.userInfo?.id,
      })
      this.ctx.body = new PageResponseModel({
        success: true,
        message: '查询成功',
        data: res,
      });
    } catch (error) {
      this.ctx.body = new PageResponseModel({
        success: false,
        // @ts-ignore
        message: error && error.toString(),
      });
    }
  }

  @roleAuthority(UserRoleEnum.developer)
  public async update() {
    const { ctx } = this;
    const { body } = ctx.request;
    const errors = this.app.validator.validate(
      {
        repository_name: { type: 'string',required: true },
        source_branch: { type: 'string',required: true },
        branch_type: { type: 'string',required: true },
        branch_name: { type: 'string',required: true },
        repository_https: { type: 'string',required: true },
        branch_usage: { type: 'string',required: false },
        assign_members: { type: 'string',required: true },
        assign_members_id: { type: 'string',required: true },
      },
      body,
    )
    if (errors) {
      this.ctx.body = new ResponseModel({
        success: false,
        data: errors,
        message: '参数错误',
      });
      return;
    }
    try {

      const res = await this.ctx.service.branch.editBranchApply({
        ...body,
        audit_status: auditStatusEnum.waiting,
        creator_id: this.userInfo?.id,
      });
      this.ctx.body = new ResponseModel({
        success: true,
        data: res,
        message: '修改成功',
      });
    } catch (error) {
      this.ctx.body = new ResponseModel({
        success: false,
        // @ts-ignore
        message: error && error.toString(),
      });
    }
  }
}
